package com.fa4j.common.base.util;

import java.util.Collection;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.function.BiConsumer;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * 字段填充工具类
 */
public class FillUtil {

    public static <O, S, T> void fillField(O obj, Function<O, S> source, BiConsumer<O, T> target, Function<S, T> converter) {
        S sourceValue = source.apply(obj);
        if (sourceValue != null) {
            T targetValue = converter.apply(sourceValue);
            target.accept(obj, targetValue);
        }

    }

    public static <O, S, T> void fillField(Collection<O> objs, Function<O, S> source, BiConsumer<O, T> target, Function<Set<S>, Map<S, T>> converter) {
        Set<S> sources = objs.stream().map(source).filter(Objects::nonNull).collect(Collectors.toSet());
        if (sources.isEmpty()) {
            return;
        }
        Map<S, T> map = converter.apply(sources);
        for (O obj : objs) {
            S sourceValue = source.apply(obj);
            if (sourceValue != null && map.containsKey(sourceValue)) {
                target.accept(obj, map.get(sourceValue));
            }
        }
    }


}
